<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ajax</title>
</head>
<body>
    <button id="btn">获取数据</button>
    <div id="result"></div>
    <script>
        btn.onclick = function () {
            //创建一个新的XMLHttpRequest对象
            var xhr = new XMLHttpRequest();
            //异步发送get请求 true同步 false异步
            xhr.open("GET", "./json/data.json", false);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var data = JSON.parse(xhr.responseText);
                    console.log(data);
                    document.getElementById("result").innerHTML = JSON.stringify(data);
                }
            };
            //只在readyState为4时才会执行
            xhr.onload = function () {
                if (xhr.status === 200) {
                    console.log("请求成功");
                } else {
                    console.log("请求失败");
                }
            };
            xhr.send();
            console.log("请求开始");
        };
    </script>
</body>
</html>